package com.jugheadzhou.kafka.producer.service;

import com.jugheadzhou.kafka.core.enums.KafkaMessageTypeEnum;
import com.jugheadzhou.kafka.core.logger.AsyncKafkaLogger;
import com.jugheadzhou.kafka.core.utils.JsonUtil;
import com.jugheadzhou.kafka.producer.dto.PatientBaseDto;
import com.jugheadzhou.kafka.producer.entity.PatientBase;
import com.jugheadzhou.kafka.producer.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @author jugheadzhou
 * @date 2021-09-22
 */
@Slf4j
@Service
public class PatientBaseService {

    private static final String FILE_NAME = "D:\\患者信息.txt";

    /**
     * 保存患者信息
     *
     * @param dto
     */
    public Integer save(PatientBaseDto dto) {
        log.info("开始保存患者信息:{}", dto);
        // 1. 参数验证
        validation(dto);
        // 2. 业务操作
        FileWriter fw = null;
        BufferedWriter bw = null;
        FileReader fr = null;
        BufferedReader br = null;
        List<String> list = null;
        try {
            PatientBase base = new PatientBase();
            BeanUtils.copyProperties(dto, base);
            // 插入患者
            fw = new FileWriter(FILE_NAME, true);
            bw = new BufferedWriter(fw);
            bw.append(JsonUtil.object2String(base)).append("\n");
            bw.flush();

            // 读取患者
            fr = new FileReader(FILE_NAME);
            br = new BufferedReader(fr);
            String line;
            list = new ArrayList<>();
            while ((line = br.readLine()) != null){
                list.add(line);
            }
            log.info("当前患者数量：{}", list.size());
            // 3. 数据归档
            // 打印日志，并发送至Kafka
            AsyncKafkaLogger.info(KafkaMessageTypeEnum.MRH_PRINT, base);
            // 4. 返回
            return list.size();
        } catch (Exception e) {
            log.error("保存患者信息发送", e);
        } finally {
            // 关闭流
            try {
                if (bw != null) {
                    bw.close();
                }
                if (fw != null) {
                    fw.close();
                }
                if (br != null) {
                    br.close();
                }
                if (fr != null) {
                    fr.close();
                }
            } catch (IOException e) {
                log.error("关闭流异常：", e);
            }
            // 清除集合
            if (!CollectionUtils.isEmpty(list)){
                list.clear();
            }
        }
        log.info("保存患者信息结束:{}", dto);
        return 0;
    }

    /**
     * 参数验证
     *
     * @param dto
     */
    private void validation(PatientBaseDto dto) {
        if (StringUtils.isBlank(dto.getPatientName())){
            throw new BusinessException("患者姓名不能为空");
        }
        if (dto.getAge() == null || dto.getAge() < 0){
            throw new BusinessException("患者年龄输入不能为空或者小于1");
        }
    }

}
